import { isArray, isString } from 'lodash-es'
import { ref, watchEffect } from 'vue'
import { appConfig, BaseType, Data, http, PageIn } from '../index'
import { useLoading } from './useLoading'


export function useAutoComplete(props: Data, pageIn: PageIn, emit: any, isNumber: boolean, url: string, apiFn?: any) {
  const multiple = isArray(props.modelValue)
  const model = ref(props.modelValue)
  watchEffect((): void => {
    if (multiple) {
      model.value = props.modelValue.map((id: BaseType) => (isNumber && Number(id)) || id)
    } else {
      if (isString(props.modelValue)) {
        if (props.modelValue === '') {
          model.value = null
        } else {
          model.value = (isNumber && Number(props.modelValue)) || props.modelValue
        }
      } else {
        model.value = props.modelValue
      }
    }
  })

  const api = async (pin: any, ctn?: string): Promise<any> => {
    if (apiFn) {
      return apiFn(url, pin, ctn)
    } else {
      const tmp: any = await http.post(url, pin, { cancelTokenName: ctn })
      return tmp[appConfig.page.rows]
    }
  }

  const options = ref([])

  const onChange = (val: any): void => {
    emit('update:modelValue', val)
    if (multiple) {
      emit(
        'change',
        options.value.filter(row => val.includes(row[appConfig.data.key])),
      )
    } else {
      emit(
        'change',
        options.value.find(item => val === item[appConfig.data.key]),
      )
    }
  }

  const [onLoad, loading] = useLoading(async (keyword: string): Promise<void> => {
    pageIn.keyword = keyword

    let arr = []
    if (multiple) {
      if (model.value.length) {
        arr = await api({ pageNo: 1, pageSize: model.value.length, params: { ids: model.value } })
      }
    } else {
      if (model.value) {
        arr = await api({
          pageNo: 1,
          pageSize: 1,
          params: { [appConfig.data.key]: model.value },
        })
      }
    }

    options.value = arr.concat((await api(pageIn)).filter((row: any) => !arr.find((item: any): boolean => item[appConfig.data.key] === row[appConfig.data.key])))
  }, true)

  const onClear = (): void => {
    pageIn.keyword = ''
    onLoad()
  }

  return {
    loading,
    model,
    onChange,
    onClear,
    onLoad,
    options,
  }
}
